<template>
  <div id="contestProblemView">
    <a-row :gutter="[24, 24]">
      <!-- 题目信息 -->
      <a-col :md="12" :xs="24">
        <a-tabs default-active-key="problem">
          <a-tab-pane key="problem" title="题目">
            <a-card v-if="contestProblem" :title="contestProblem.title">
              <template #extra>
                <a-space>
                  <a-tag color="blue">{{ contestProblem.displayId }}</a-tag>
                  <a-tag color="green">{{ contestProblem.score }} 分</a-tag>
                </a-space>
              </template>

              <div class="problem-content">
                <div v-html="contestProblem.content"></div>
              </div>
            </a-card>
          </a-tab-pane>

          <a-tab-pane key="submissions" title="提交记录">
            <a-table
              :columns="submissionColumns"
              :data="mySubmissions"
              :pagination="false"
            >
              <template #result="{ record }">
                <a-tag :color="getResultColor(record.judgeResult)">
                  {{ record.judgeResult }}
                </a-tag>
              </template>
              <template #time="{ record }">
                {{ formatDateTime(record.createTime) }}
              </template>
              <template #actions="{ record }">
                <a-button size="small" @click="viewSubmission(record)">
                  查看详情
                </a-button>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-col>

      <!-- 代码编辑器 -->
      <a-col :md="12" :xs="24">
        <a-card title="提交代码">
          <template #extra>
            <a-space>
              <a-select
                v-model="submitForm.language"
                placeholder="选择编程语言"
                style="width: 120px"
              >
                <a-option value="JAVA">Java</a-option>
                <a-option value="CPP">C++</a-option>
                <a-option value="C">C</a-option>
                <a-option value="PYTHON">Python</a-option>
              </a-select>
              <a-button
                type="primary"
                :loading="submitting"
                @click="submitCode"
              >
                提交
              </a-button>
            </a-space>
          </template>

          <CodeEditor
            :value="submitForm.code"
            :language="submitForm.language"
            :handle-change="onCodeChange"
            :height="500"
          />
        </a-card>
      </a-col>
    </a-row>

    <!-- 提交详情对话框 -->
    <a-modal
      v-model:visible="submissionModalVisible"
      title="提交详情"
      width="800px"
      :footer="false"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="提交时间">
          {{ formatDateTime(selectedSubmission?.createTime) }}
        </a-descriptions-item>
        <a-descriptions-item label="编程语言">
          {{ selectedSubmission?.language }}
        </a-descriptions-item>
        <a-descriptions-item label="判题结果">
          <a-tag :color="getResultColor(selectedSubmission?.judgeResult || '')">
            {{ selectedSubmission?.judgeResult }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="执行时间">
          {{ selectedSubmission?.judgeInfo?.time }}ms
        </a-descriptions-item>
        <a-descriptions-item label="内存使用">
          {{ selectedSubmission?.judgeInfo?.memory }}KB
        </a-descriptions-item>
        <a-descriptions-item label="错误信息">
          {{ selectedSubmission?.errorMessage || "无" }}
        </a-descriptions-item>
      </a-descriptions>

      <a-divider />

      <h4>提交代码</h4>
      <pre class="code-block">{{ selectedSubmission?.code }}</pre>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import message from "@arco-design/web-vue/es/message";
import moment from "moment";
import CodeEditor from "@/components/CodeEditor.vue";
import { ContestControllerService } from "../../generated";
import type {
  ContestProblem,
  ContestSubmitDTO,
  QuestionSubmit,
} from "../../generated";

const route = useRoute();
const router = useRouter();
const store = useStore();

// 数据
const contestProblem = ref<ContestProblem>();
const mySubmissions = ref<QuestionSubmit[]>([]);
const submitting = ref(false);
const submissionModalVisible = ref(false);
const selectedSubmission = ref<QuestionSubmit>();

// 提交表单
const submitForm = ref<ContestSubmitDTO>({
  language: "JAVA",
  code: "",
});

// 计算属性
const contestId = computed(() => route.params.contestId as string);
const problemId = computed(() => route.params.problemId as string);

// 表格列定义
const submissionColumns = [
  {
    title: "提交时间",
    slotName: "time",
    width: 180,
  },
  {
    title: "语言",
    dataIndex: "language",
    width: 100,
  },
  {
    title: "结果",
    slotName: "result",
    width: 100,
  },
  {
    title: "操作",
    slotName: "actions",
    width: 100,
  },
];

// 加载题目信息
const loadProblemInfo = async () => {
  try {
    const res = await ContestControllerService.getContestProblemsUsingGet(
      parseInt(contestId.value)
    );
    if (res.code === 0) {
      const problem = res.data?.find((p) => p.id === parseInt(problemId.value));
      if (problem) {
        contestProblem.value = problem;
        // 从本地存储加载代码
        const savedCode = localStorage.getItem(
          `contest_${contestId.value}_problem_${problemId.value}`
        );
        if (savedCode) {
          submitForm.value.code = savedCode;
        }
      } else {
        message.error("题目不存在");
        router.back();
      }
    } else {
      message.error("加载失败，" + res.message);
    }
  } catch (error) {
    message.error("加载失败");
  }
};

// 加载我的提交记录
const loadMySubmissions = async () => {
  try {
    const res = await ContestControllerService.getContestSubmissionsUsingGet(
      parseInt(contestId.value),
      1,
      50
    );
    if (res.code === 0) {
      // 过滤当前题目的提交记录
      const problemSubmissions =
        res.data.records?.filter(
          (s) => s.contestProblemId === parseInt(problemId.value)
        ) || [];

      // 获取详细的提交信息
      const detailedSubmissions = await Promise.all(
        problemSubmissions.map(async (submission) => {
          try {
            const detailRes =
              await ContestControllerService.getSubmissionDetailUsingGet(
                parseInt(contestId.value),
                submission.id!
              );
            return detailRes.data;
          } catch (error) {
            return null;
          }
        })
      );

      mySubmissions.value = detailedSubmissions.filter((s) => s !== null);
    }
  } catch (error) {
    message.error("加载提交记录失败");
  }
};

// 提交代码
const submitCode = async () => {
  if (!submitForm.value.code?.trim()) {
    message.warning("请输入代码");
    return;
  }

  submitting.value = true;
  try {
    // 保存代码到本地存储
    localStorage.setItem(
      `contest_${contestId.value}_problem_${problemId.value}`,
      submitForm.value.code
    );

    const submitData = {
      ...submitForm.value,
      contestId: parseInt(contestId.value),
      contestProblemId: parseInt(problemId.value),
      problemId: contestProblem.value?.problemId,
    };

    const res = await ContestControllerService.submitContestProblemUsingPost(
      parseInt(contestId.value),
      submitData
    );

    if (res.code === 0) {
      message.success("提交成功");
      // 重新加载提交记录
      loadMySubmissions();
    } else {
      message.error("提交失败，" + res.message);
    }
  } catch (error) {
    message.error("提交失败");
  } finally {
    submitting.value = false;
  }
};

// 代码变化处理
const onCodeChange = (value: string) => {
  submitForm.value.code = value;
};

// 查看提交详情
const viewSubmission = (submission: QuestionSubmit) => {
  selectedSubmission.value = submission;
  submissionModalVisible.value = true;
};

// 工具函数
const getResultColor = (result: string) => {
  const colorMap: Record<string, string> = {
    AC: "green",
    WA: "red",
    TLE: "orange",
    MLE: "purple",
    RE: "red",
    CE: "gray",
  };
  return colorMap[result] || "default";
};

const formatDateTime = (time: string) => {
  return moment(time).format("YYYY-MM-DD HH:mm:ss");
};

// 页面加载
onMounted(() => {
  loadProblemInfo();
  loadMySubmissions();
});
</script>

<style scoped>
#contestProblemView {
  max-width: 1400px;
  margin: 0 auto;
  padding: 16px;
}

.problem-content {
  line-height: 1.6;
}

.problem-content h1,
.problem-content h2,
.problem-content h3 {
  margin-top: 16px;
  margin-bottom: 8px;
}

.problem-content p {
  margin-bottom: 8px;
}

.problem-content pre {
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
}

.code-block {
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  overflow-x: auto;
  font-family: "Courier New", monospace;
  font-size: 14px;
  line-height: 1.4;
  max-height: 400px;
  overflow-y: auto;
}
</style>
